# 
# Helper methods for specs
#

require 'fileutils'
require 'tmpdir'
require 'rubygems'
require 'neo4j'


# suppress all warnings
$NEO_LOGGER.level = Logger::ERROR

NEO_STORAGE = '/Users/chriswroe/NetBeansProjects/derision/etc/db/neo'
LUCENE_INDEX_LOCATION = '/Users/chriswroe/NetBeansProjects/derision/etc/db/lucene'


def reset_config
  # reset configuration
  Lucene::Config.delete_all
  Lucene::Config[:storage_path] = LUCENE_INDEX_LOCATION
  Lucene::Config[:store_on_file] = true

  Neo4j::Config.delete_all
  Neo4j::Config[:storage_path] = NEO_STORAGE
end

reset_config

def delete_db
  # delete db on filesystem
  FileUtils.rm_rf Neo4j::Config[:storage_path]
  FileUtils.rm_rf Lucene::Config[:storage_path] unless Lucene::Config[:storage_path].nil?
end

def start
  # stop it - just in case
  Neo4j::Transaction.finish if Neo4j::Transaction.running?

  Neo4j.stop

  delete_db

  reset_config
  
  # start neo

end


def stop
  # make sure we finish all transactions
  Neo4j::Transaction.finish if Neo4j::Transaction.running?
  
  Neo4j.stop

end


def undefine_class(*clazz_syms)
  clazz_syms.each do |clazz_sym|
    Object.instance_eval do
      begin
        Neo4j::Indexer.remove_instance const_get(clazz_sym)
        remove_const clazz_sym
      end if const_defined? clazz_sym
    end
  end
end


def clazz_from_symbol(classname_as_symbol)
  classname_as_symbol.to_s.split("::").inject(Kernel) do |container, name|
    container.const_get(name.to_s)
  end
end

def print_sub(node,level, max_level, dir) # :nodoc:
    spaces = "  " * level
    node_class = (node[:_classname].nil?) ? Neo4j::Node.to_s : node[:_classname]
    node_desc = "#{spaces}neo_id=#{node.neo_id} #{node_class}"
    node.props.each_pair {|key, value| node_desc << " #{key}='#{value}'"}
    puts node_desc

    if (level != max_level)
      node.rels(dir).each do |rel|
        cascade_desc = ""
        cascade_desc << "cascade in: #{rel[:_cascade_delete_incoming]}" if rel.property?(:_cascade_delete_incoming)
        cascade_desc << "cascade out: #{rel[:_cascade_delete_outgoing]}" if rel.property?(:_cascade_delete_outgoing)
        print_sub(rel.other_node(node),level + 1, max_level, dir)
      end
    end
  end
